package org.jsshbroadcast.ssh;

import com.jcraft.jsch.*;
import java.io.*;
import org.jsshbroadcast.SysConfig;
import org.jsshbroadcast.jsbException.*;

/**
 *
 * @author Eduardo Folly
 */
public class ClasseSSH {

    private String usuario;
    private String senha;
    private String servidor;
    private int porta;
    private JSch jsch;
    private Session session;
    private InformacaoUsuario ui;
    private Channel channel;

    public ClasseSSH(String user, String password, String server, int port) {
        usuario = user;
        senha = password;
        servidor = server;
        porta = port;
        jsch = new JSch();
    }

    public void conectar() throws JSchException {
        session = jsch.getSession(usuario, servidor, porta);
        ui = new InformacaoUsuario(senha);
        session.setUserInfo(ui);
        session.connect(SysConfig.getInstance().getSshTimeOut());
    }

    public String executar(String comando) throws IOException, SSHExitStatusException, JSchException {
        channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(comando);

        channel.setInputStream(null);

        OutputStream errOut = new ByteArrayOutputStream();
        ((ChannelExec) channel).setErrStream(errOut);

        InputStream in = channel.getInputStream();

        channel.connect();

        byte[] tmp = new byte[1024];
        String s = new String();
        while (true) {
            while (in.available() > 0) {
                int i = in.read(tmp, 0, 1024);
                if (i < 0) {
                    break;
                }
                s += new String(tmp, 0, i);
            }
            if (channel.isClosed()) {
                if (channel.getExitStatus() > 0) {
                    String errmsg = errOut.toString();
                    throw new SSHExitStatusException(errmsg.substring(0, errmsg.length() - 1));
                }
                break;
            }
            try {
                Thread.sleep(500);
            } catch (Exception ee) {
            }
        }
        channel.disconnect();
        return s;
    }

    public void desconectar() throws JSchException {
        session.disconnect();
    }

    private static class OutputStreamImpl extends OutputStream {

        public OutputStreamImpl() {
        }

        @Override
        public void write(int b) throws IOException {
            throw new UnsupportedOperationException("Não suportado ainda.");
        }
    }
}
